package ads.pin.pinmon.dal;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import ads.pin.pinmon.entity.Creature;
import ads.pin.pinmon.entity.Player;

public class PlayerCreatureDAO {
	// TODO Add method to update player creatures.
	private EntityManager em = new EntityManager() {

		@Override
		public Object treatResultSet(ResultSet resultSet) throws SQLException {
			Player player = new Player();

			player.setCreatures(getAllPlayerCreatures(player.getId()));
			return player;
		}
	};

	/**
	 * Retorna todas as criaturas pertencentes ao jogador de ID = ?.
	 * 
	 * @param id
	 *            Identificador do jogador.
	 * @return Criaturas que pertencem ao jogador.
	 * @throws SQLException
	 */
	@SuppressWarnings("unchecked")
	public List<Creature> getAllPlayerCreatures(Integer id) throws SQLException {
		String sql = " select distinct creature_id from player_creature where player_id = ?";

		return (List<Creature>) em.getResultList(sql, id);
	}

	/**
	 * Salva na tabela de juncao o jogador e suas criaturas.
	 * 
	 * @param player
	 *            Player a ser salvo.
	 * @throws SQLException
	 */
	public void savePlayerCreature(Player player) throws SQLException {
		String sql = " insert into player_creature (player_id, creature_id) "
				+ " values (?, ?) ";

		// Executa a query salvando o id do jogador e o id de cada criatura.
		for (Creature creature : player.getCreatures())
			em.executeQuery(sql, player.getId(), creature.getId());

	}

}
